package com.dyb.demo.test_thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Exchanger;
/**
 * Exchanger交换线程数据
 * exchanger.exchange() 会产生阻塞，直到获取到交换的数据
 * @author dyb
 * @date 2019/12/12
 */
public class ExchangerTest {

    public static void main(String[] args) {

        final Exchanger<List<Integer>> exchanger = new Exchanger<List<Integer>>();
        Thread thread1 = new Thread(() -> {
            List<Integer> list = new ArrayList<>(4);
            list.add(1);
            list.add(2);
            try {
                List<Integer> thread2List = exchanger.exchange(list);
                System.out.println("thread1" + list + ", thread2" + thread2List);
            } catch (InterruptedException e) {
            }
        }, "thread1");
        thread1.start();

        Thread thread2 = new Thread(() -> {
            List<Integer> list = new ArrayList<>(4);
            list.add(3);
            list.add(4);
            try {
                List<Integer> thread1List = exchanger.exchange(list);
                System.out.println("thread1" + thread1List + ", thread2" + list);
            } catch (InterruptedException e) {
            }
        }, "thread2");
        thread2.start();
    }
}
